package com.mini.service;

import com.google.common.base.Joiner;
import com.mini.config.COSConfig;
import com.mini.util.CalendarUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

/**
 * <p></p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author zl
 * @version 1.0
 * @date Created in 2019/11/7 20:26
 * @copyright: Copyright (c) founders
 */

@Service
@Slf4j
public class TencentUploadService {

    @Value("${aliyun.oss.img.maxSize:500000}")
    private Long uploadImgMaxSize;
    @Value("${aliyun.oss.img.resizePathParam:x-oss-process=image/auto-orient,1/quality,q_}")
    private String imgResizePathParam;

    private final String baseUrl = "mini/wehub";

    @Value("${ali.test.states}")
    private String testStates;

    @Value("${tencent.mini.bucketname}")
    private String miniBucketName;
    @Value("${tencent.mini.domain}")
    private String miniImgDomain;


    @Autowired
    private COSConfig cosConfig;

    @Autowired
    private COSClient cosClient;

    public String uploadManageFile(MultipartFile file){
        String subModelPath = "manage/" + CalendarUtil.getDateString(new Date(),"yyyyMMdd");
        return uploadOssFile(file, baseUrl, subModelPath, false);
    }

    public String uploadChatFile(MultipartFile file, String groupId, String userId ){
        //TODO 再细化/chat/yyyyMMdd/userId/uuid.xxx
        String subModelPath = "chat/" + CalendarUtil.getDateString(new Date(),"yyyyMMdd");
        return uploadOssFile(file,baseUrl, subModelPath, false);
    }



    /**
     * 公共上传
     * 举例：
     * modelPath：tongzhuo
     * subModelPath：jubao
     */
    public String uploadOssFile(MultipartFile file, String modelPath, String subModelPath, boolean needResize) {

        if (file == null) {
            return null;
        }

        if (StringUtils.isBlank(file.getOriginalFilename())
                || file.getOriginalFilename().lastIndexOf(".") == -1
                || file.getOriginalFilename().lastIndexOf(".") == file.getOriginalFilename().length() - 1) {

            log.info("未知文件类型");
            return null;
        }

        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());

        try {

            // 存储路径 格式 /modelPath/subModelPath/uuid.xxx
            String uploadRealPathDir = Joiner.on("/").join(modelPath, subModelPath).concat("/");
            String localUploadFilePath = uploadRealPathDir + UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            File tempFile = File.createTempFile(UUID.randomUUID().toString(), suffix);
            // 将MultipartFile转为File
            file.transferTo(tempFile);
            PutObjectResult putObjectResult = cosClient.putObject(cosConfig.getBucketName(), localUploadFilePath, tempFile);
            String imgPath = cosConfig.getImgDomain() + "/" + localUploadFilePath;
            if (needResize) {
                try {
                    Long imageOriginSize = file.getSize();
                    log.info("imgPath:[{}], imageOriginSize:{}", imgPath, imageOriginSize);
                    if (uploadImgMaxSize < imageOriginSize) {
                        log.info("resize to uploadImgMaxSize for {}", imgPath);

                        int intPercent = new BigDecimal(Double.valueOf(uploadImgMaxSize))
                                .divide(new BigDecimal(Double.valueOf(imageOriginSize)), 2, BigDecimal.ROUND_HALF_UP)
                                .remainder(BigDecimal.ONE).multiply(new BigDecimal(Double.valueOf(100))).intValue();

                        imgPath = imgPath + "?" + imgResizePathParam + intPercent;
                    }
                } catch (Exception e) {
                    log.error("", e);
                }
            }
            tempFile.delete();
            return imgPath;

        } catch (Exception e) {
            log.error("", e);
            return null;
        }

    }

    public String uploadImg(MultipartFile file,String path){
        String imgUrl = "";
        try {
            // 获取图片后缀名
            String resultSuffix = "";
            String originalFileName = file.getOriginalFilename();
            if (!org.apache.commons.lang3.StringUtils.isBlank(originalFileName)) {
                int start = originalFileName.lastIndexOf(".");
                start = start == -1 ? 0 : start;
                String suffix = originalFileName.substring(start, originalFileName.length());
                resultSuffix = suffix.startsWith(".") ? suffix : "." + suffix;
            }
            resultSuffix = org.apache.commons.lang3.StringUtils.isBlank(resultSuffix) ? ".jpg" : resultSuffix;
            if(".jpeg".equalsIgnoreCase(resultSuffix)){
                resultSuffix = ".jpg";
            }

            String newName = System.currentTimeMillis()+ resultSuffix;
            if("test".equalsIgnoreCase(testStates)){
                path = "test/" + path;
            }
            String localUploadFilePath =  path + newName;
            //上传到ali oss
            InputStream inputStream = file.getInputStream();
            PutObjectResult putObjectResult = cosClient.putObject(miniBucketName, localUploadFilePath, inputStream,new ObjectMetadata());

            imgUrl = miniImgDomain + "/" + localUploadFilePath ;

        } catch (Exception e) {
            log.error("上传图片报错，path = {} , e = {}", path , e);
        }
        return imgUrl;
    }


    /**
     *
     * @param content
     * @param localUploadFilePath
     * @return
     */
    public String uploadContent2OSS(String content,String localUploadFilePath,String domain){
        String imgUrl = "";
        try {

            if("test".equalsIgnoreCase(testStates)){
                localUploadFilePath = "test/" + localUploadFilePath;
            }


            PutObjectResult putObjectResult = cosClient.putObject(miniBucketName, localUploadFilePath, content);

            imgUrl = domain + "/" + localUploadFilePath ;

        } catch (Exception e) {
            log.error("上传文件报错，path = {} , e = {}", localUploadFilePath , e);
        }
        return imgUrl;
    }
    public void deleteFile(String fileUrl) {

        try {

            if (StringUtils.isBlank(fileUrl)) {
                return;
            }
            fileUrl = fileUrl.replace(cosConfig.getImgDomain() + "/", "");
            if (fileUrl.indexOf("?") > 0) {
                fileUrl = fileUrl.substring(0, fileUrl.indexOf("?") - 1);
            }

            cosClient.deleteObject(cosConfig.getBucketName(), fileUrl);

        } catch (Exception e) {
            log.error("删除图片异常，fileUrl={},e={}", fileUrl, e);
        }

    }



    public void deleteFilesByDayPath(String dayPath) {
        try {

            if (StringUtils.isBlank(dayPath)) {
                return;
            }

            ListObjectsRequest listObjectsRequest =  new ListObjectsRequest(cosConfig.getBucketName(), "tongzhuoimagecheck/" +dayPath+ "/", null, null, 1000);
            ObjectListing objectListing = null;
            long n = 0;
            do {
                objectListing = cosClient.listObjects(listObjectsRequest);
                if(CollectionUtils.isNotEmpty(objectListing.getObjectSummaries())){
                    String[] keys = objectListing.getObjectSummaries().stream()
                            .map(COSObjectSummary::getKey).toArray(String[]::new);
                    DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(cosConfig.getBucketName());
                    deleteObjectsRequest.withKeys(keys);
                    DeleteObjectsResult deleteObjectsResult = cosClient.deleteObjects(deleteObjectsRequest);
                    log.info("批量删除图片 {} 个", deleteObjectsResult.getDeletedObjects().size());
                    n += deleteObjectsResult.getDeletedObjects().size();
                }

            }while (CollectionUtils.isNotEmpty(objectListing.getObjectSummaries()) );
            log.info("总共批量删除图片 {} 个", n);
        } catch (Exception e) {
            log.error("批量删除图片异常，dayPath={},e={}", dayPath, e);
        }
    }

}
